package com.wyw.leetcode.learning.simple;

/**
 * leetcode topic 724
 * 寻找数组的中心坐标
 *
 * @Author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
public class Topic724 {
    public static void main(String[] args) {
        int[] nums = new int[] {1,7,3,6,5,6};
//        int[] nums = new int[] {1,2,3};
//        int[] nums = new int[] {2,-1,1};
        System.out.println(pivotIndex1(nums));
    }

    public static int pivotIndex(int[] nums) {
        int length = nums.length;
        for(int i=0; i<length; i++) {
            int sumBefore = 0;
            int sumAfter = 0;
            for (int j = i-1; j>=0; j--) {
                sumBefore += nums[j];
            }
            for(int j = i+1; j<length; j++) {
                sumAfter += nums[j];
            }
            if(sumAfter == sumBefore) {
                return i;
            }
        }
        return -1;
    }

    public static int pivotIndex1(int[] nums) {
        int length = nums.length;
        int sumBefore = 0;
        int sumAfter = 0;
        for(int i = 1; i<length; i++) {
            sumAfter += nums[i];
        }
        for(int i=0; i<length; i++) {
            if(sumAfter == sumBefore) {
                return i;
            }
            if(i == length-1)
                sumAfter = 0;
            else
                sumAfter -= nums[i+1];
            sumBefore += nums[i];
        }
        return -1;
    }

    public static int pivotIndex2(int[] nums) {
        int sum = 0;
        int sumleft = 0;
        int len = nums.length;
        for(int i=0;i<len;i++)
            sum += nums[i];
        for(int i=0;i<len;i++)
        {
            if(sumleft*2+nums[i]==sum)
                return i;
            sumleft+=nums[i];
        }
        return -1;
    }


}
